<template>
	<view class="c-msg-iframe">
		<scroll-view scroll-y="true" @click="onScrollToBottom" :scroll-into-view="viewIndex" scroll-with-animation='true'
		 :style="{height:wHeight+'px'}">
			<view v-show="curPageIndex!=0" @click="onLoadMore" class="c-msg-more">点击加载更多</view>
			<view v-for="(item,index) in listMsg" class="c-msg-list" :key="index">
				<view class="c-msg-list-dt">
					<text v-show="index==0?true:((_msgFormatTime(item.sendtime)==(index ? _msgFormatTime(listMsg[index-1].sendtime):_msgFormatTime(listMsg[0].sendtime)))?false:true)">{{_msgFormatTime(item.sendtime)}}</text>
				</view>
				<view :class="(item.fromid==userid)?'c-msg-list-right':'c-msg-list-left'">
					<view class="c-msg-list-user">
						<image :src="item.fromid==userid?userHeaderImgUrl:fromUserHeaderImgUrl" mode="widthFix"></image>
						<!-- {{item.fromid==userid?_retSlgName(username):_retSlgName(fromUserName)}} -->
					</view>
					<view class="c-msg-list-msg">
						<view class="c-msg-list-msg-name">
							{{item.fromid==userid?"":fromUserName}}
						</view>
						<view class="c-msg-list-msg-content" v-html="item.content.replace(reg,_newContent)">
							<!-- {{item.content.replace(reg,_newContent)}} -->
						</view>
					</view>
				</view>
			</view>
			<!-- 可滚动到底部的view标签 -->
			<view id="botMsg"></view>
		</scroll-view>
		<view class="c-msg">
			<view class="c-msg-send-btn">
				<view class="btn-left">
					<textarea v-model="msg" @input="onMsgChange" />
					</view>
				<view class="btn-right">
					<image @click="onShowMsg(0)" src="@/static/images/icons/icon-face-btn.png" mode="widthFix"></image>
					<image @click="onShowMsg(1)" src="@/static/images/icons/icon-add-btn.png" mode="widthFix"></image>
					<button :disabled="blnDisabled_s" @click="onSendMsg()" type="primary" class="btn-send">发送</button>
				</view>
			</view>
			<view class="c-msg-face" v-show="blnShowMsg.idx==0&&blnShowMsg.face">
				<view class="face-title">
					所有表情
				</view>
				<view class="face-imgs">
					<view class="imgs-img" @click="onClkFace(item.tip)" v-for="(item,index) in imgs" :key="index">
						<image lazy-load="true" :src="_retStrFace(item.idx)" mode="widthFix"></image>
					</view>
				</view>
				<view class="face-btns">
					<view class="btn-del" @click="onDelMsg()">清除</view>
				</view>
			</view>
			<view class="c-msg-file" v-show="blnShowMsg.idx==1&&blnShowMsg.add">
				<view class="file-type">
					<view class="type-pics" @click="onClkAct(index)" v-for="(item,index) in file" :key="index">
						<view class="pics-img">
							<image lazy-load="true" :src="item.url" mode="widthFix"></image>
						</view>
						<view class="pics-title">
							{{item.title}}
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	var arrMsg = [];
	var strOld = "";
	var msg_slice_data = [];
	export default {
		data() {
			return {
				listMsg: [],
				dt: (new Date).getMinutes() + ":" + (new Date).getSeconds(),
				viewIndex: 'botMsg',
				curPageIndex: 0,
				fromid: -1,
				fromUserName: uni.getStorageSync("fromUserName") ? uni.getStorageSync("fromUserName") : "",
				userid: JSON.parse(uni.getStorageSync("userLoginData")).UserID,
				username: JSON.parse(uni.getStorageSync("userLoginData")).UserName,
				userHeaderImgUrl: "/static/images/imgs/male.jpg",
				fromUserHeaderImgUrl: "/static/images/imgs/female.jpg",
				msg: "",
				wHeight: 0,
				blnDisabled_s:true,
				reg: /\[[\S]{1,3}\]/gi,
				blnShowMsg: {
					face: false,
					add: false,
					idx: -1
				},
				file: [{
						url: "/static/images/icons/icon-picture.png",
						title: "照片"
					},
					{
						url: "/static/images/icons/icon-camera.png",
						title: "拍摄"
					},
					{
						url: "/static/images/icons/icon-pickup.png",
						title: "文件"
					},
					{
						url: "/static/images/icons/icon-location.png",
						title: "位置"
					}
				],
				imgs: [{
					idx: 0,
					tip: '[微笑]'
				}, {
					idx: 1,
					tip: '[撇嘴]'
				}, {
					idx: 2,
					tip: '[色]'
				}, {
					idx: 3,
					tip: '[发呆]'
				}, {
					idx: 4,
					tip: '[得意]'
				}, {
					idx: 5,
					tip: '[流泪]'
				}, {
					idx: 6,
					tip: '[害羞]'
				}, {
					idx: 7,
					tip: '[闭嘴]'
				}, {
					idx: 8,
					tip: '[睡]'
				}, {
					idx: 9,
					tip: '[大哭]'
				}, {
					idx: 10,
					tip: '[尴尬]'
				}],
				tips: []
			};
		},
		watch: {
			listMsg: {
				handler(o, n) {
					// 清空未读数据;
					this.chat.delCount(this.fromid);
					// 计算总数量
					this.chat.countSum();
				},
				deep: true
			},
			msg: {
				handler(o, n) {
					strOld = this.msg;
					arrMsg = [];
				}
			}
		},
		onLoad(options) {
			// 生成表情数据
			this.imgs.forEach(item => {
				this.tips.push(item.tip)
			})
			// 显示标题文字
			uni.setNavigationBarTitle({
				title: "正在与 " + this.fromUserName + " 对话中"
			})
			// 获取可视高度
			uni.getSystemInfo({
				success: (res) => {
					this.wHeight = res.windowHeight - 60;
				}
			})
			// 获取ConnUserId
			let fromid = options.ConnUserId;
			this.fromid = fromid;

			// 清空未读数据;
			this.chat.delCount(fromid);
			// 计算总数量
			this.chat.countSum();

			// 显示初始数据
			this.listMsg = this.getInitData(fromid, true);

			// #ifndef APP-PLUS
			//定义接收数据
			if (this.chat.ws && this.chat.ws.readyState == 1) {
				this.chat.ws.addEventListener("message", res => {
					let _res = JSON.parse(res.data)
					switch (_res.code) {
						case 2:
							break;
						case 3:
							this.listMsg = this.getInitData(fromid, false);
							// 滚动到底部
							this.scrToBot();
							break;
					}
				})
			} else {
				this.noConn();
			}
			// #endif

			// #ifdef APP-PLUS
			//定义接收数据
			if (this.chat.ws && this.chat.ws.readyState == 1) {
				this.chat.ws.onMessage(res => {
					let _res = JSON.parse(res.data)
					switch (_res.code) {
						case 2:
							break;
						case 3:
							this.listMsg = this.getInitData(fromid, false);
							// 滚动到底部
							this.scrToBot();
							break;
					}
				})
			} else {
				this.noConn();
			}
			// #endif
		},
		methods: {
			_retSlgName(v) {
				return (v) ? v.substr(0, 1) : "";
			},
			_retStrFace(idx) {
				return `/static/images/imgs/${idx}.gif`;
			},
			_newContent(tip) {
				// 查找数据
				let idx = this.tips.indexOf(tip);
				// 返回对应元素
				return `<img src="./static/images/imgs/${idx}.gif" alt="" style="vertical-align:middle;margin:0 2px" />`;
			},
			_msgFormatTime(dt) {
				// 格式化显示时间
				return this.retMsgFormatTime(dt);
			},
			onLoadMore() {
				if (this.curPageIndex > 0) {
					this.curPageIndex = parseInt(this.curPageIndex) - 1;
					this.listMsg = [...msg_slice_data[this.curPageIndex], ...this.listMsg];
				}
			},
			onClkFace(tip) {
				arrMsg.push(tip);
				this.msg = strOld + arrMsg.toString().replace(/,/g, '');
				this.blnDisabled_s = this.checkIsEmpty(this.msg,"0000");
			},
			onDelMsg() {
				arrMsg.pop();
				this.msg = arrMsg.toString().replace(/,/g, '');
				this.blnDisabled_s = this.checkIsEmpty(this.msg,"0000");
			},
			onScrollToBottom() {
				if (this.blnShowMsg.face) {
					this.blnShowMsg.face = false;
					this.wHeight = parseInt(this.wHeight) + 120;
					this.scrToBot();
				}
				if (this.blnShowMsg.add) {
					this.blnShowMsg.add = false;
					this.wHeight = parseInt(this.wHeight) + 120;
					this.scrToBot();
				}
			},
			onClkAct(index) {
				// console.log(index)
				switch (index) {
					case 0:
						uni.chooseImage({
							count: 6, //默认9
							sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
							sourceType: ['album'], //从相册选择
							success: function(res) {
								console.log(JSON.stringify(res.tempFilePaths));
							}
						});
						break;
					case 1:
						uni.chooseVideo({
							count: 1,
							sourceType: ['camera'],
							success: function(res) {
								console.log(res.tempFilePath);
							}
						});
						break;
					case 2:
						uni.chooseFile({
							count: 6, //默认100
							extension: ['.zip', '.doc'],
							success: function(res) {
								console.log(JSON.stringify(res.tempFilePaths));
							}
						});
						break;
					case 3:
						break;
				}
			},
			onShowMsg(idx) {
				if (idx) {
					this.blnShowMsg.idx = idx;
					this.blnShowMsg.add = !this.blnShowMsg.add;
					if (this.blnShowMsg.add && !this.blnShowMsg.face) {
						this.wHeight = parseInt(this.wHeight) - 120;
						this.scrToBot();
						strOld = this.msg;
					} else {
						if (!this.blnShowMsg.add) {
							this.wHeight = parseInt(this.wHeight) + 120;
						}
						if (this.blnShowMsg.face) {
							this.blnShowMsg.face = false;
						}
					}
				} else {
					this.blnShowMsg.idx = idx;
					this.blnShowMsg.face = !this.blnShowMsg.face;
					if (this.blnShowMsg.face && !this.blnShowMsg.add) {
						this.wHeight = parseInt(this.wHeight) - 120;
						this.scrToBot();
						strOld = this.msg;
					} else {
						if (!this.blnShowMsg.face) {
							this.wHeight = parseInt(this.wHeight) + 120;
						}
						arrMsg = [];
						if (this.blnShowMsg.add) {
							this.blnShowMsg.add = false;
						}
					}
				}
			},
			// 发送内容
			onSendMsg() {
				if (this.msg != "") {
					if (this.chat.ws && this.chat.ws.readyState == 1) {
						
						this.msg = this.msg.replace(/\n/g,"<br>")
						let _newData = JSON.stringify({
							"msgtype": "2",
							"fromid": JSON.parse(uni.getStorageSync("userLoginData")).UserID,
							"toid": this.fromid,
							"content": this.msg,
							"sendtime": (new Date()).getTime(),
							"code": 3
						})

						// #ifndef APP-PLUS
						this.chat.ws.send(_newData);
						// #endif

						// #ifdef APP-PLUS
						this.chat.ws.send({
							data: _newData
						})
						// #endif

						// 发送成功后操作
						this.listMsg = this.getAddData(_newData, false);
						// 增加最后一次发送内容
						this.chat.addMsg(this.fromid, this.msg);
						this.msg = "";
						this.blnDisabled_s = true;
						arrMsg = [];
						strOld = "";
						this.scrToBot();

					} else {
						this.noConn();
					}
				} else {
					uni.showToast({
						icon: "none",
						title: "不能发送空白消息！"
					})
				}
			},
			// 监测内容变化
			onMsgChange(e) {
				this.msg = e.detail.value;
				this.blnDisabled_s = this.checkIsEmpty(this.msg,"0000");
			},
			// 对话框滚动到最底部
			scrToBot() {
				this.viewIndex = "";
				//设置viewIndex值，使聊天滚动到底部
				this.$nextTick(() => {
					this.viewIndex = "botMsg";
				})
			},
			// 无网提示
			noConn() {
				uni.showToast({
					icon: "none",
					title: "断网了，请稍后再试！",
					success: () => {
						setTimeout(res => {
							uni.reLaunch({
								url: "./MsgUserList"
							})
						}, 1000)
					}
				})
			},	
			// 获取页码分割数据
			getSliceData(arr) {
				let arrLength = arr.length; // 数组长度
				let num = 10; // 每页显示 10 条
				let index = 0;
				let newArr = [];
				for (let i = 0; i < arrLength; i++) {
					if (i % num === 0 && i !== 0) { // 可以被 10 整除
						newArr.push(arr.slice(index, i));
						index = i;
					};
					if ((i + 1) === arrLength) {
						newArr.push(arr.slice(index, (i + 1)));
					}
				}
				return newArr;
			},
			// 获取旧数据
			getInitData(fromid, blnFirst) {
				// 获取聊天记录
				let msgList = this.chat.msglist;
				// 根据id号过滤数据
				let _msglist = msgList.filter((item, index) => {
					return (item.fromid == fromid) || (item.toid == fromid)
				})
				if (blnFirst) {
					// 分割数组
					msg_slice_data = this.getSliceData(_msglist);
					// 记录展示分页的起始页码
					this.curPageIndex = msg_slice_data.length > 1 ? msg_slice_data.length - 1 : 0;
					// 返回第一条记录
					return msg_slice_data[this.curPageIndex];
				} else {
					// 最后记录索引号
					let _idxlast = _msglist.length > 1 ? _msglist.length - 1 : 0;
					// 获取新增加内容
					let _objmsg = JSON.stringify(_msglist[_idxlast]);
					return this.getAddData(_objmsg, true);
				}
				// 滚动到底部
				this.scrToBot();
			},
			// 获取添加后的新数据
			getAddData(newObj, blnRec) {
				// 获取原有数据
				let _msgList = this.chat.msglist;
				// 获取单个对话数据
				let _slgList = (this.listMsg==undefined)?[]:this.listMsg;
				// 接收新数据
				let _obj = JSON.parse(newObj);
				if (!blnRec) {
					// 添加至原对象中
					_msgList.push(_obj);
				}
				// 添加至对话数据
				_slgList.push(_obj);
				// 更新本地数据
				uni.setStorageSync("msgList", JSON.stringify(_msgList));
				// 返回对话内容
				return _slgList;
			}
		}
	}
</script>

<style>
	page {
		background-color: #F1F5F6;
	}

	.file-type {
		display: flex;
		margin-top: 30rpx;
		justify-content: space-around;
	}

	.pics-img {
		background-color: #FFFFFF;
		width: 82rpx;
		height: 82rpx;
		border-radius: 20rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 20rpx;
	}

	.pics-img image {
		width: 64rpx;
	}

	.pics-title {
		text-align: center;
		font-size: 24rpx;
	}

	.c-msg-more {
		text-align: center;
		font-size: 26rpx;
	}

	.c-msg {
		position: fixed;
		width: 100%;
		bottom: 0;
		left: 0;
		border: solid 0rpx red;
	}

	.c-msg-send-btn {
		border-top: solid 0rpx #eeee;
		padding: 20rpx 0;
		display: flex;
		background-color: #F6F6F6;
		justify-content: space-around;
	}

	.c-msg-face,
	.c-msg-file {
		border: solid 0rpx red;
		padding: 16rpx 26rpx 20rpx 26rpx;
		position: relative;
		background-color: #ECECEC;
		height: 220rpx;
	}

	.face-title {
		margin: 0 0 20rpx 20rpx;
		font-size: 28rpx;
	}

	.face-imgs {
		border: solid 0rpx blue;
		justify-content: space-between;
		display: flex;
		flex-wrap: wrap;
	}

	.face-imgs:after {
		content: "";
		height: 0;
		width: 62%;
	}

	.imgs-img {
		flex: 0 0 12.5%;
		border: solid 0rpx red;
		margin-bottom: 10rpx;
		text-align: center;
	}

	.face-btns {
		display: flex;
		position: absolute;
		right: 20rpx;
		bottom: 30rpx;
	}

	.btn-del{
		margin-right: 10rpx;
		padding: 10rpx 26rpx;
		border-radius: 12rpx;
		font-size: 26rpx;
		background-color: #FFFFFF;

	}

	.btn-send {
		margin: 0 6rpx 0 0;
		background-color: #4497e1;
		color: #ffffff;
		border-radius: 12rpx;
		font-size: 26rpx;
	}

	.imgs-img image {
		width: 48rpx;
	}

	.btn-left textarea {
		border: solid 2rpx #eee;
		padding: 16rpx;
		background-color: #fff;
		border-radius: 16rpx;
		margin-left: 10rpx;
		height: auto;
		max-height: 63px;
		width: 430rpx;
		overflow-y: hidden;
	}

	.btn-right {
		display: flex;
		justify-content: space-around;
		border: solid 0rpx red;
		width: 100%;
		align-items: center;
	}

	.btn-right image {
		width: 50rpx;
		height: 50rpx;
	}

	scroll-view {
		height: 1000rpx;
	}

	.c-msg-list {
		padding: 20rpx;
		color: #000000;
	}

	.c-msg-list-dt {
		display: flex;
		justify-content: center;
		margin: 20rpx;
	}

	.c-msg-list-dt text {
		text-align: center;
		padding: 0 12rpx;
		font-size: 26rpx;
		background-color: #F7F9F8;
		color: #99999d;
		border-radius: 16rpx;
		border: solid 2rpx #E5E5E5;
	}

	.c-msg-list-left {
		display: flex;
	}

	.c-msg-list-right {
		display: flex;
		flex-direction: row-reverse;
	}

	.c-msg-list-right .c-msg-list-user {
		background-color: #ECECEC;
		border-radius: 16rpx;
		color: #ffffff;
		text-align: center;
		width: 80rpx;
		height: 80rpx;
		font-size: 36rpx;
		line-height: 80rpx;
		float: right;
	}

	.c-msg-list-user image {
		width: 80rpx;
		border-radius: 16rpx;
	}

	.c-msg-list-msg-name {
		font-size: 26rpx;
	}

	.c-msg-list-left .c-msg-list-msg-name {
		margin-left: 20rpx;
	}

	.c-msg-list-right .c-msg-list-msg-content {
		max-width: 560rpx;
		word-wrap: break-word;
		background-color: #BBE5FE;
		margin-right: 20rpx;
		padding: 16rpx;
		border-radius: 16rpx 8rpx 16rpx 16rpx;
	}

	.c-msg-list-left .c-msg-list-user {
		background-color: #ECECEC;
		border-radius: 16rpx;
		color: #ffffff;
		text-align: center;
		width: 80rpx;
		height: 80rpx;
		line-height: 80rpx;
	}

	.c-msg-list-left .c-msg-list-msg-content {
		max-width: 560rpx;
		word-wrap: break-word;
		background-color: #fff;
		margin-left: 20rpx;
		padding: 16rpx;
		border-radius: 8rpx 16rpx 16rpx 16rpx;
	}

	#botMsg {
		height: 20rpx;
	}
</style>
